package com.seeyon.apps.kk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;

import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;

public class HeheHttpUtil {
	
	private static final Log log = CtpLogFactory.getLog(HeheHttpUtil.class);
	
	/**
	 * 调用orc接口请求
	 * @param file
	 * @return
	 */
	public static String sendOcrRequest(String name, File file){
		String content = "";
		HttpClientUtil client = new HttpClientUtil(2*60*1000);
		FileInputStream fis = null;
		try{
			client.openPost(Constants.HEHE_OCR_URL);
			client.setRequestHeader("Content-Type", "application/octet-stream");
			client.setRequestHeader("connection", "Keep-Alive");
			client.setRequestHeader("app-key", Constants.HEHE_APPKEY);
			client.setRequestHeader("app-secret",Constants.HEHE_APPSECRET);
			if (null != file && file.exists()) {
				fis = new FileInputStream(file);
				client.setRequestBodyFile(fis);
	        }
			int status = client.send();
	        if (status == HttpStatus.SC_OK) {
	        	Map map = client.getResponseJsonAsObject(Map.class);
	        	if(map.containsKey("code") && "200".equals(ParamUtil.getString(map, "code", ""))){
	        		return map.get("result").toString();
	        	} else {
	        		content = ParamUtil.getString(map, "message", "");
	        	}
	        } else {
	        	content = "网络请求异常或其他异常.";
	        }
	        return null;
		} catch(IOException e){
			content = "网络请求异常或其他异常.";
			log.error("##客开日志", e);
			return null;
		} finally {
			IOUtils.closeQuietly(fis);
			client.close();
			
			saveLog(name, "调用orc认证接口", content);
		}
	}
	
	/**
	 * 获取启信宝报告
	 * @param id
	 * @return 
	 * eid	企业ID
	 * name	企业名称
	 * eportType	报告类型
	 * pdfUrl	pdf格式报告下载地址
	 */
	public static Map getReportStatusById(String agentName, String id){
		String content = "";
		HttpClientUtil client = new HttpClientUtil(2*60*1000);
		try{
			client.openPost(Constants.HEHE_OTHER_GET);
			Map map = new HashMap();
			map.put("id", id);
			map.put("appkey", Constants.HEHE_OTHER_APPKEY);
			client.setRequestBodyJson(map);
			int status = client.send();
	        if (status == HttpStatus.SC_OK) {
	        	map.clear();
	        	map = client.getResponseJsonAsObject(Map.class);
	        	if(map.containsKey("status") && "200".equals(ParamUtil.getString(map, "status", ""))){
	        		return JSONUtil.parseJSONString(map.get("data").toString(), Map.class);
	        	} else {
	        		content = ParamUtil.getString(map, "message", "");
	        	}
	        } else {
	        	content = "网络请求异常或其他异常.";
	        }
		} catch(IOException e) {
			content = "网络请求异常或其他异常.";
			log.error("##客开日志", e);
		} finally {
			saveLog(agentName, "获取启信宝报告", content);
			client.close();
		}
		return null;
	}
	
	/**
	 * 企业名称生成报告
	 * @param param
	 * @return
	 * id	报告id
	 * fileNames	上传的文件名列表
	 */
	public static Map generateReportByName(String agentName, Map param){
		String content = null;
		HttpClientUtil client = new HttpClientUtil(2*60*1000);
		try{
			client.openPost(Constants.HEHE_OTHER_NEW);
			Map body = new HashMap();
			body.put("name", agentName);
			body.put("appkey", Constants.HEHE_OTHER_APPKEY);
			body.put("type", "FULL");//SIMPLE-简单版，FULL-完整版
			body.put("info", param);
			client.setRequestBodyJson(body);
			int status = client.send();
	        if (status == HttpStatus.SC_OK) {
	        	Map map = client.getResponseJsonAsObject(Map.class);
	        	if(map.containsKey("status") && "200".equals(ParamUtil.getString(map, "status", ""))){
	        		return JSONUtil.parseJSONString(map.get("data").toString(), Map.class);
	        	} else {
	        		content = ParamUtil.getString(map, "message", "");
	        		Map params = new HashMap();
	        		params.put("error", content);
	        		return params;
	        	}
	        } else {
	        	content = "网络请求异常或其他异常.";
	        }
		} catch(IOException e) {
			log.error("##客开日志", e);
			content = "网络请求异常或其他异常.";
		} finally {
			saveLog(agentName, "企业名称生成报告", content);
			client.close();
		}
		return null;
	}

	private static void saveLog(String name, String inface, String content){
		//启信宝调用日志
		  Map<String, Object> logMap=new HashMap<String, Object>();
		  logMap.put("接口名称", inface);
		  logMap.put("调用模块", "启信宝接口");//致远插件、启信宝接口
		  logMap.put("经销商名称", name);
		  logMap.put("调用人", AppContext.getCurrentUser() == null ? name: AppContext.getCurrentUser().getName());
		  if(Strings.isEmpty(content)){
			  logMap.put("调用状态", "成功");//成功、失败、异常
			  logMap.put("失败说明","");
		  } else {
			  if("网络请求异常或其他异常.".equals(content)){
				  logMap.put("调用状态", "异常");//成功、失败、异常
			  } else {
				  logMap.put("调用状态", "失败");//成功、失败、异常
			  }
			  logMap.put("失败说明",content);
		  }
		  logMap.put("调用时间", DateUtil.currentDate());
		  FormDataBaseManager qiangsManager = (FormDataBaseManager) AppContext.getBean("kkBaseFormManager");
		  try {
			  qiangsManager.saveUnflowData(Constants.qxbLogformCode, Constants.createUser, logMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("##客开日志", e);
		}
	}
}
